'
' StoreNuke.Net -  http:'www.storenuke.net
' Copyright (c) 2005
' by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http:'www.willowtreesoftware.com )
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'

Imports System.Net
Imports System.Reflection
Imports System
Imports System.Web
Imports System.IO
Imports StoreNuke.StarterKit.Commerce
Imports StoreNuke.StarterKit.Commerce.Components

Public Class StorePayPalIPN
    Inherits System.Web.UI.Page

    Protected WithEvents productList As System.Web.UI.WebControls.Repeater

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Dim strName As String 'Form Post Name
            Dim objStream As StreamWriter 'Confirmation EMail to PayPal
            Dim blnValid As Boolean = True 'Transaction status (complete, pending, failed, etc)
            Dim strTransactionID As String 'PayPal Transaction Number
            Dim intShipToID As Integer 'The ShipTo ID of the ShipTo Address
            'Dim intUserID As Integer  'UserID of the Purchaser
            Dim dblAmount As Decimal 'Total Sale
            Dim TaxTotal As Decimal
            Dim ShipTotal As Decimal
            Dim strCartID As String 'Shopping Cart ID
            Dim strEmail As String 'Customers EMail
            Dim customString() As String
            'Dim strBody As String ' Message
            Dim strPayPalID As String 'Get PayPal EMail ID
            Dim ct As New CartProcessingControl

            Dim strPost As String = "cmd=_notify-validate"
            For Each strName In Request.Form
                Dim strValue As String = Request.Form(strName)
                Select Case strName
                    Case "payment_status" ' verify the status
                        If ((strValue <> "Completed") And (strValue <> "Pending")) Then
                            blnValid = False
                        End If
                    Case "txn_id" ' verify the transaction id for duplicates
                        strTransactionID = strValue
                    Case "receiver_email" ' verify the PayPalId
                        strPayPalID = strValue
                    Case "mc_gross" ' verify the price
                        dblAmount = Decimal.Parse(strValue)
                    Case "item_number" ' get the CartID for Migration
                        strCartID = CStr(Int32.Parse(strValue))
                    Case "custom" ' get the UserID
                        Try
                            intShipToID = Int32.Parse(strValue)
                        Catch
                            intShipToID = Int32.Parse(strCartID)
                        End Try
                        'Case "invoice" ' ShiptToID
                        '    intShipToID = strValue
                    Case "shipping" ' get the Shipping Ammount
                        ShipTotal = Decimal.Parse(strValue)
                    Case "tax" ' get the Tax Ammount
                        TaxTotal = Decimal.Parse(strValue)
                    Case "email" ' get the email
                        strEmail = strValue
                End Select
                'details += strName & ": " & strValue & vbCrLf
                ' reconstruct post for postback validation
                strPost += String.Format("&{0}={1}", strName, HTTPPOSTEncode(strValue))
            Next

            If blnValid Then
                Dim returnValue As Integer = ct.ProcessCart(Convert.ToInt32(intShipToID), strCartID)
                'If (returnValue > -1) Then
                'End If
            End If

            ' postback to verify the source
            If blnValid Then
                Dim objRequest As HttpWebRequest = CType(WebRequest.Create("https://www.paypal.com/cgi-bin/webscr"), HttpWebRequest)
                objRequest.Method = "POST"
                objRequest.ContentLength = strPost.Length
                objRequest.ContentType = "application/x-www-form-urlencoded"

                objStream = New StreamWriter(objRequest.GetRequestStream())
                objStream.Write(strPost)
                objStream.Close()

                Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)
                Dim sr As StreamReader
                sr = New StreamReader(objResponse.GetResponseStream())
                Dim strResponse As String = sr.ReadToEnd()
                sr.Close()

                Select Case strResponse
                    Case "VERIFIED"
                    Case Else
                        ' possible fraud
                        blnValid = False
                End Select
            End If
        Catch
        End Try
    End Sub

    ' encodes a URL for posting to an external site
    Public Function HTTPPOSTEncode(ByVal strPost As String) As String
        strPost = Replace(strPost, "\", "")
        strPost = System.Web.HttpUtility.UrlEncode(strPost)
        strPost = Replace(strPost, "%2f", "/")
        HTTPPOSTEncode = strPost
    End Function

End Class